#include "offline_message_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>

#include "base/logging.h"
#include "base/json_escape.h"
#include "im/common/common.h"

#include "call_center_cache.h"

namespace imserver {
namespace fcgi {

bool OfflineMessageRequest::Response() {
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }
  ParseUserIdentity();

  MessageResult res;
  if (effective_id() > 0) {
    MessageHistoryAdapter::Instance().GetOfflineMessages(effective_id(), 0, 50, &res, 2);
    LOG_INFO("GetOfflineMessages uid=" << effective_id() << " size=" << res.results.size());

    if (!res.results.empty()) {
      std::vector<int64_t> seq_ids;
      for(size_t i = 0; i < res.results.size(); ++i) {
        seq_ids.push_back(res.results[i].seq_id);
      }
      MessageHistoryAdapter::Instance().SetReadById(seq_ids, effective_id(), 2);
    }
  } else {
    LOG_WARN("GetOfflineMessages bad param, uid=" << effective_id());
  }
  
  std::stringstream rsp_header;
  rsp_header << "Content-type: text/javascript; charset=utf-8\r\n" << "\r\n";
  FCGX_PutS(rsp_header.str().c_str(), fcgi_out_);

  std::stringstream rsp_body;
  std::string callback = ParseCallback();

  if (!callback.empty()) {
    // 开头空格是 IE bug fix
    rsp_body << ' ' << callback << "(";
  }

  rsp_body << "{\"total\":" << res.count
           << ',';

  rsp_body << "\"msg_list\":[";

  bool is_waiter = CallCenterCache::Instance().IsWaiter(effective_id());
  for (size_t i = res.results.size(); i > 0; --i) {
    int message_type = MessageType(res.results[i - 1]);
    if (MSG_TYPE_BANG_ORDER == message_type && effective_id() == res.results[i - 1].sender) {
      continue;
    }
    rsp_body << "{\"sender\":" << res.results[i - 1].sender
             << ",\"receiver\":" << res.results[i - 1].receiver
             << ",\"mtype\":" << message_type
             << ",\"timestamp\":" << res.results[i - 1].timestamp
             << ",\"message\":\"" << base::JsonEscape(res.results[i - 1].body);

    if (is_waiter && res.results[i].__isset.via_shop) {
      rsp_body << "\", \"via_shop\":\"" << res.results[i].via_shop;
      if (res.results[i].__isset.via_shop_name) {
        rsp_body << "\", \"via_shop_name\":\"" << base::JsonEscape(res.results[i].via_shop_name);
      }
      if (res.results[i].__isset.via_shop_url) {
        rsp_body << "\", \"via_shop_url\":\"" << res.results[i].via_shop_url;
      }
    }
    rsp_body << "\"}";
    if ((i - 1) > 0) {
      rsp_body << ',';
    }
  }
  rsp_body << "]}";

  if (!callback.empty()) {
    rsp_body << ")";
  }

  LOG_DEBUG("OfflineMessageRequest rsp=" << rsp_body.str());

  FCGX_PutS(rsp_body.str().c_str(), fcgi_out_);
  return true;
}

}
}


